// 提交代码到游戏
// 多人合作时，开发者不要将提交自己代码的特定命令配置在 package.json 中，而是使用此脚本

const shelljs = require('shelljs')
const { select, confirm } = require('@inquirer/prompts')
const path = require('path')
const userConfig = require(path.resolve(__dirname, '../.secret.json'))

const allUsers = Object.keys(userConfig)
// 是否混淆代码，带有 -t 参数时混淆代码
const isTerser = process.argv.includes('-t')

const selectUser = async () => {
    try {
        return await select({
            message: '请选择要提交的玩家',
            choices: allUsers.map((name) => {
                return {
                    name,
                    value: name,
                }
            }),
        })
    } catch (error) {
        return ''
    }
}

const exec = (user) => {
    let cmd = `npx rollup -cw --environment DEST:${user}`
    if (isTerser) {
        cmd += ',TERSER'
    }
    shelljs.exec(cmd)
}

const submit = async () => {
    let user = process.argv[2]

    if (userConfig[user]) {
        exec(user)
        return
    }

    user = allUsers.find((name) => name.includes(user))
    if (user) {
        if (await confirm({ message: `确定提交玩家 ${user} 吗？` })) {
            exec(user)
            return
        }
    }

    user = await selectUser()
    if (user) {
        exec(user)
    }
}

submit()
